<template>
  <div class="user-list">
    <!-- 搜索 -->
    <div class="filter-container">
      <el-input
        v-model="query.first_name"
        size="mini"
        placeholder="输入用户姓名"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handSearch"
      />
      <el-input
        v-model="query.department_name"
        size="mini"
        placeholder="输入部门名称"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handSearch"
      />
      <el-button
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-search"
        @click="handSearch"
        >搜索</el-button
      >
      <el-button
        class="filter-item"
        size="mini"
        type="defalut"
        icon="el-icon-close"
        @click="clearParam"
        plain
        >清空</el-button
      >
    </div>
    <!-- 工具栏 -->
    <div class="btngroup">
      <el-button
        class="filter-item"
        size="small"
        type="primary"
        icon="el-icon-plus"
        @click="handDialogShow"
        >新增
      </el-button>
      <el-button
        class="filter-item"
        size="small"
        icon="el-icon-edit"
        @click="handDialogEdit"
        :disabled="multipleSelection.length !== 1"
        >修改</el-button
      >
      <el-button
        class="filter-item"
        size="small"
        icon="el-icon-delete"
        @click="handDelete"
        :disabled="multipleSelection.length !== 1"
        >删除</el-button
      >
      <el-button
        class="filter-item"
        size="small"
        @click="dialogGroupVisible = true"
        >群组管理</el-button
      >
      <el-button
        class="filter-item"
        size="small"
        @click="handleExport"
        >导出</el-button
      >
    </div>
    <!--用户数据-->
    <div class="task-items">
      <el-table
        :data="usersList"
        size="small"
        stripe
        style="width: 100%; text-align: center"
        v-loading="listLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          min-width="100"
          align="left"
        ></el-table-column>
        <el-table-column
          prop="first_name"
          label="姓名"
          min-width="100"
          align="left"
        ></el-table-column>
        <el-table-column
          prop="job_no"
          label="工号"
          min-width="100"
          align="left"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="电子邮箱"
          min-width="130"
          align="left"
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="电话号码"
          min-width="100"
          align="left"
        ></el-table-column>
        <el-table-column
          prop="department_name"
          label="部门"
          min-width="130"
          align="left"
        ></el-table-column>
        <el-table-column
          prop="label_name"
          label="职称"
          min-width="100"
          align="left"
        ></el-table-column>
        <el-table-column label="状态" min-width="100">
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.is_active"
              :disabled="row.username === 'admin'"
              @change="changeStatus($event, row.id)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" min-width="159">
          <template slot-scope="{ row }">
            <span>{{ parseTime(row.date_joined) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="140" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handTagUpdate(scope.row)"
            ></el-button>
            <el-button
              size="small"
              icon="el-icon-delete"
              @click="handTagDelete(scope.row.id)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        v-show="total > 0"
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        :layout="'total, prev, pager, next'"
        @pagination="handlePage"
      />
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="570px"
    >
      <el-form
        ref="form"
        :model="form"
        :inline="true"
        :rules="rules"
        label-width="65px"
        label-position="right"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            size="small"
            placeholder="登陆账号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="form.password"
            size="small"
            placeholder="2~20个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="job_no">
          <el-input
            v-model="form.job_no"
            size="small"
            placeholder="工号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="first_name">
          <el-input
            v-model="form.first_name"
            size="small"
            placeholder="姓名"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="form.phone"
            size="small"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="form.email"
            size="small"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门">
          <!-- <el-select v-model="form.department" class="select" size="small" placeholder="请选择部门">
            <el-option v-for="(item,index) in departmentList" :label="item.dt_name" :value="item.id" :key="index">
            </el-option>
          </el-select> -->
          <treeselect
            class="select"
            placeholder="请选择部门"
            v-model="form.department"
            :options="departmentList"
            :normalizer="normalizer"
          />
        </el-form-item>
        <el-form-item label="职称">
          <el-select
            v-model="form.label"
            filterable
            allow-create
            class="select"
            size="small"
            placeholder="请选择职称"
          >
            <el-option
              v-for="(item, index) in labelsList"
              :label="item.name"
              :value="item.id"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="form.groups"
            multiple
            class="select"
            size="small"
            placeholder="请选择角色"
          >
            <el-option
              v-for="(item, index) in roleList"
              :label="item.name"
              :value="item.id"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年假">
          <el-input
            v-model="form.annual_leave"
            style="width: 185px"
            :disabled="true"
            class="disabled"
            size="small"
            placeholder="0"
          ></el-input>
        </el-form-item>
        <el-form-item class="workTime" label="工作时间">
          <el-date-picker
            size="small"
            value-format="yyyy-MM"
            v-model="form.join_work_date"
            type="month"
            placeholder="选择月"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.is_active">
            <el-radio :label="true">激活</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="small"
          >取 消</el-button
        >
        <el-button type="primary" @click="handSubmit" size="small"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 群组管理 -->
    <el-dialog title="群组管理" :visible.sync="dialogGroupVisible" width="80%">
      <share-group ref="shareGroup" :showSelection="false" :showBack="false" />
    </el-dialog>
  </div>
</template>
<script>
import { isvalidPhone } from "@/utils/validate";
import {
  getAllUser,
  getUserLabel,
  getUserDepartment,
  getAllRole,
  postCreateUser,
  patchUpdateUser,
  deleteUser,
} from "@/api/user.js";
import { mapGetters } from "vuex";
import { filterObj, parseTime } from "@/utils/index.js";

import Treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "UserList",
  computed: {
    ...mapGetters(["name", "roles", "id"]),
    dialogTitle() {
      const title = this.isEdit ? "编辑" : "新建";
      return title + "用户";
    },
  },
  components: {
    pagination: () => import("@/components/Pagination"),
    Treeselect,
    ShareGroup: () => import("@/views/markSys/components/ShareGroup"),
  },
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!isvalidPhone(value)) {
        callback(new Error("请输入正确的11位手机号码"));
      } else {
        callback();
      }
    };
    return {
      total: 0,
      currentPage: 1,
      size: 10,
      listLoading: true,
      query: {
        page: 1,
        first_name: "",
        department_name: "",
      },
      form: {},
      formCopy: {}, // 编辑时复制row
      normalizer(node) {
        return {
          id: node.id,
          label: node.dt_name,
          children: node.child,
        };
      },
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入用户密码",
            trigger: "blur",
          },
          {
            min: 2,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        // job_no: [{
        //   required: true,
        //     message: '请输入工号',
        //     trigger: 'blur'
        //   }
        // ],
        // email: [{
        //     required: true,
        //     message: '请输入邮箱地址',
        //     trigger: 'blur'
        //   },
        //   {
        //     type: 'email',
        //     message: '请输入正确的邮箱地址',
        //     trigger: 'blur'
        //   }
        // ],
        // phone: [{
        //   required: true,
        //   trigger: 'blur',
        //   validator: validPhone
        // }],
        role: [
          {
            required: true,
            message: "请选择用户角色",
            trigger: "blur",
          },
        ],
      },
      dialogFormVisible: false,
      isEdit: false,
      multipleSelection: [],
      usersList: [],
      labelsList: [], // 职称列表
      departmentList: [], // 部门列表
      roleList: [], // 角色列表
      dialogGroupVisible: false,
      groupSelection: [], // 选择群组
    };
  },
  mounted() {
    this.requestLabels();
    this.requestDepartments();
    this.requestRoles();
    this.requestusersList();
  },
  methods: {
    parseTime,
    // 清空搜索
    clearParam() {
      this.query.first_name = "";
      this.query.department_name = "";
    },
    // 搜索
    handSearch() {
      this.query.page = 1;
      this.requestusersList();
    },
    handlePage(val) {
      this.query.page = val.page;
      this.requestusersList();
    },
    // 点击切换用户状态
    changeStatus(flag, id) {
      patchUpdateUser(id, {
        is_active: flag,
      }).then((res) => {
        if (res && res.data && res.data.username) {
          this.$notify({
            title: "成功",
            message: "修改用户状态成功",
            type: "success",
            duration: 3000,
          });
          this.requestusersList();
        }
      });
    },
    // 点击删除按钮
    handDelete() {
      this.handTagDelete(this.multipleSelection[0].id);
    },
    // 删除用户
    handTagDelete(id) {
      this.$confirm("此操作将删除用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteUser(id).then((res) => {
          this.$notify({
            title: "成功",
            message: "删除用户成功",
            type: "success",
            duration: 3000,
          });
          this.requestusersList();
        });
      });
    },
    // 点击编辑按钮
    handDialogEdit() {
      this.handTagUpdate(this.multipleSelection[0]);
    },
    // 编辑
    handTagUpdate(row) {
      this.isEdit = true;
      // 转换角色
      this.form = JSON.parse(JSON.stringify(row));
      this.formCopy = JSON.parse(JSON.stringify(row));
      this.dialogFormVisible = true;
    },
    // 提交创建请求
    handSubmit() {
      // 密码强度正则，至少包含两种字符，长度不少于6位
      const regex =
        /(?!^[0-9]{6,12}$)(?!^[a-z]{6,12}$)(?!^[A-Z]{6,12}$)^[0-9A-Za-z]{6,12}$/;
      this.$refs.form.validate((valid) => {
        if (valid) {
          const { department, password } = this.form;
          if (!department) {
            this.$message.warning("请选择所属部门");
            return;
          }
          if (password && !regex.test(password)) {
            this.$message.warning("密码为长度6~12位，必须包含数字和字母");
            return;
          }
          let _form = this.form;
          const { label, ...reset } = _form;
          // 如果是自定义职称
          if (typeof label === "string") {
            reset.label_name = label;
            _form = { ...reset };
          }

          if (this.isEdit) {
            const param = {};
            Object.keys(_form).forEach((e) => {
              let flag = false;
              if (typeof _form[e] === "string") {
                flag = _form[e] !== this.formCopy[e];
              } else {
                flag =
                  JSON.stringify(_form[e]) !== JSON.stringify(this.formCopy[e]);
              }
              if (flag) {
                param[e] = _form[e];
              }
            });
            // 如果编辑未改变则不提交
            if (!Object.keys(param).length) return;
            patchUpdateUser(_form.id, param).then((res) => {
              if (res && res.data && res.data.username) {
                this.dialogFormVisible = false;
                this.$notify({
                  title: "成功",
                  message: "编辑用户成功",
                  type: "success",
                  duration: 3000,
                });
                this.isEdit = false;
                this.requestusersList();
                // 刷新职称
                this.requestLabels();
              }
            });
          } else {
            postCreateUser(_form).then((res) => {
              if (res && res.data && res.data.username) {
                this.dialogFormVisible = false;
                this.$notify({
                  title: "成功",
                  message: "创建用户成功",
                  type: "success",
                  duration: 3000,
                });
                this.isEdit = false;
                this.requestusersList();
                // 刷新职称
                this.requestLabels();
              }
            });
            // .catch(error =>{
            //   console.log(error)
            //   if (error.response) {
            //     const result = error.response.data
            //     Object.keys(result).forEach(
            //         key =>{
            //           this.$message.error(result[key][0])
            //         }
            //       )
            //   }
            // })
          }
        }
      });
    },
    // 打开对话框
    handDialogShow() {
      this.isEdit = false;
      this.form = {
        is_active: true,
        groups: [3],
        department: this.departmentList[0].id,
      };
      this.dialogFormVisible = true;
    },
    // 表格多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 请求部门信息
    requestRoles() {
      getAllRole().then((res) => {
        this.roleList = res.data.results;
      });
    },
    // 请求职称信息
    requestLabels() {
      getUserLabel().then((res) => {
        this.labelsList = res.data.results;
      });
    },
    // 请求部门信息
    requestDepartments() {
      getUserDepartment({ owner: this.id }).then((res) => {
        this.departmentList = res.data;
      });
    },
    // 请求用户列表信息
    requestusersList() {
      this.query.owner = this.id;
      const param = filterObj(this.query);
      getAllUser(param).then((res) => {
        this.usersList = res.data.results;
        this.total = res.data.count;
        this.listLoading = false;
      });
    },
    //通过属性名获取值。
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if(j === 'date_joined'){
            return v[j] ? v[j].split('T')[0] : ''
          }
          return v[j];
        })
      );
    },
    //导出
    handleExport() {
      const that = this 
      this.$message({
        message:'正在导出',
        type:'warning',
        duration:0
      })
      const params = {...filterObj(this.query),page_size : 100000,page:1}
      
      getAllUser(params).then((res) => {
        const dataList = res.data.results
        import("@/vendor/Export2Excel").then((excel) => {
          const header = ['姓名','登陆账号','电子邮箱','电话号码','部门','职称','创建时间'];
          const filterVal = [
            'first_name','job_no','email','phone','department_name','label_name','date_joined'
          ];
          const data = that.formatJson(filterVal, dataList);
          that.$message.closeAll()
          excel.export_json_to_excel({
            header,
            data,
            filename: "用户信息",
            autoWidth: true,
          });
        });
      });
    },
  },
};
</script>
<style lang="scss">
.user-list {
  padding: 20px 20px 45px 20px;

  .filter-container,
  .btngroup {
    margin-bottom: 10px;
  }
  .pagination {
    margin-top: 10px;
  }
  .el-form--inline .el-form-item {
    margin-bottom: 16px;
  }

  .select {
    width: 185px;
  }
  .workTime {
    label {
      width: 75px !important;
    }
    div {
      div {
        width: 175px !important;
      }
    }
  }
  .disabled {
    input {
      background-color: white !important;
      color: black !important;
    }
  }
  .vue-treeselect__input-container {
    height: 32px;
  }
}
</style>
